package r25.room;

import org.slf4j.Logger;

import r25.character.ICharacter;
import r25.engine.Event;
import r25.engine.IEvent;
import r25.engine.IEvent.EVENT;
import r25.engine.IGameInstance;
import r25.engine.IGameInstance.CHARACTER_ACTION;
import r25.tools.LoggerHelper;

/**
 * You have to leave this room with your next action or you're executed.
 * 
 * @author u211354
 * 
 */
public class TrappedChamber extends AbstractRoom {
	private static final Logger logger = LoggerHelper.getLogger();

	@Override
	public CHARACTER_ACTION onEnter(IGameInstance gi, ICharacter character)
			throws Exception {
		CHARACTER_ACTION rc = super.onEnter(gi, character);
		gi.pushEvent(new Event(EVENT.DIE_OR_LEAVE_ROOM, this, character));
		return rc;
	}

	@Override
	public void check(IGameInstance gi, boolean endOfTurn, IEvent s) {
		// may invalidate the event
		super.check(gi, endOfTurn, s);

		logger.debug("Evaluating event {}", s);
		// process only own event DIE_OR_LEAVE_ROOM
		if (!EVENT.DIE_OR_LEAVE_ROOM.equals(s.getType()) || !s.isValid()) {
			return;
		}

		ICharacter character = s.getCharacter();
		if (!character.equals(gi.getCurrentCharacter())) {
			return;
		}

		logger.debug("Evaluating character {}", character);
		logger.debug("  Event {} vs GTS {}", gi.getCharacterActionIndex(),
				s.getTimeStamp());

		boolean isNextAction = (gi.getTurnIndex() != s.getTimeStamp().getTurn())
				|| (gi.getCharacterActionIndex() != s.getTimeStamp()
						.getCharacterAction());
		if (isNextAction && character.isAlive()) {
			if (this.equals(character.getRoomIn())) {
				logger.debug("Triggered @{} event {}",
						gi.getCurrentStateTimeStamp(), s);

				// the character dies
				character.setAlive(false);
				gi.pushEvent(new Event(EVENT.DEATH, this, character));
			}

			// anyway if next action, cancel the check
			logger.debug("Invalidated @{} event {}",
					gi.getCurrentStateTimeStamp(), s);
			s.setValid(false);
		}
	}
}
